package com.onecar.carplatform.jtt.handler.base;


import com.onecar.carplatform.common.protocol.annotations.JtMsgClassUtil;
import com.onecar.carplatform.common.protocol.basics.JtMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;

/**
 * @Author : ljq
 * @Description :
 * @Date : 2021/8/23 11:04
 * @Version : 1.0
 */
@Slf4j
public class JttMsgHandler extends SimpleChannelInboundHandler<JtMessage> {

    private static final HashMap<Integer, JttMsgHandlerUtil.JttMsgHandlerInfo> handlers;

    static {
        handlers = JttMsgHandlerUtil.getClass("com.onecar.carplatform.jtt.handler.jtt808");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("exceptionCaught", cause);
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            //此实例项目只设置了读取超时时间,可以通过state分别做处理,一般服务端在这里关闭连接节省资源，客户端发送心跳维持连接
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                log.warn("客户端{}读取超时,关闭连接", ctx.channel().remoteAddress());
                ctx.close();
            } else if (state == IdleState.WRITER_IDLE) {
                log.warn("客户端{}写入超时", ctx.channel().remoteAddress());
            } else if (state == IdleState.ALL_IDLE) {
                log.warn("客户端{}读取写入超时", ctx.channel().remoteAddress());
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, JtMessage jtMessage) throws Exception {
        JttMsgHandlerUtil.JttMsgHandlerInfo handlerInfo = handlers.get((int) jtMessage.getHeader().getMsgId());
        if (handlerInfo == null) {
            log.warn("the handler for the corresponding message id {} cannot be obtained", jtMessage.getHeader().getMsgId());
            return;
        }

        JttMsgHandlerInterface handler = handlerInfo.getAClass().getDeclaredConstructor().newInstance();
        handler.channelRead0(channelHandlerContext, jtMessage);
    }
}
